package org.vectrics.recruiter.struts;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Logger;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.config.RecruitConfig;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.Person;

public class ShowProfileSummaryAction extends VectricsStrutsAction {
    private transient static Logger log = Logger.getLogger(ShowProfileSummaryAction.class);

    public String doExecute(VectricsActionData actionData) throws JspException {

        Request request = actionData.getRequest();
        String personId = request.getParameter("personId");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

        if (personId != null) {
            if ((userName != null) && (userName.trim().length() > 0)) {
                log.info("Logging in user");
                Person person = CoreServiceLocator.getPersonService().findPersonWithUserName(
                        ThreadProperties.getDomain(), userName);
                if ((person != null) && (person.getUser() != null) && (password != null)) {

                    boolean validCredentials = false;
                    if ((password != null) && (person.getUser().getPassword().equals(password))) {
                        validCredentials = true;
                    }
                    if (validCredentials) {
                        String server = RecruitConfig.getRecruitInstance().getServerIp();
                        CoreServiceLocator.getUserAuthService().loginUser(request, server, request.getContextPath(),
                                person);
                        log.info("Login Complete!");
                    } else {
                        log.info("Credentials not valid");
                        return ("failure");
                    }
                } else if (CoreServiceLocator.getUserAuthService().getAuthorizedPerson(ThreadProperties.getDomain(),
                        request) != null) {
                    return ("success");

                } else {
                    return ("failure");
                }
            } else {
                log.info("Showing profile - no login credentials specified.");
            }
        }

        return ("success");
    }

}